import { logger } from '../utils/logger';
import { Card } from '../card/base/Card';
import { CardRegistry } from '../registry/CardRegistry';
import { Room } from './Room';

export class CardPool {
	constructor(private room: Room) {}
	private pools: Record<string, Card[]> = {
		global: [],
	};

	add(name: string, cardId: string, count: number = 1): void {
		const card = CardRegistry.get(cardId);
		if (card) {
			for (let i = 0; i < count; i++) {
				card.pool = name;
				(this.pools[name] ??= []).push(card);
			}
		}
		logger.info(`CardPool: ${name} AddCard ${cardId} ${count}`);
	}

	back(card: Card) {
		if (card.pool != '') {
			const newCard = CardRegistry.get(card.cardId);
			if (newCard) {
				newCard.pool = card.pool;
				(this.pools[card.pool] ??= []).push(newCard);
			}
		}
	}

	draw(name: string, global: boolean = false): Card | undefined {
		const pool: Card[] = (this.pools[name] ??= []);
		if (pool.length == 0) global = true;
		if (Math.random() <= (!global ? 1 : 0.5)) {
			const index = Math.floor(Math.random() * pool.length);
			const card = pool[index];
			pool.splice(index, 1);
			return card;
		} else {
			return this.draw('global');
		}
	}
}
